package com.tuo51.bytedance.miniapp.controller;

import com.google.common.collect.Maps;
import com.tuo51.bytedance.miniapp.config.BdMaProperties;
import com.tuo51.bytedance.miniapp.service.BDRemoteCallService;
import com.tuo51.bytedance.vo.BDCode2SessionRequest;
import com.tuo51.bytedance.vo.BDCode2SessionResponseData;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.vo.users.StaffVO;
import com.tuo51.foudation.constant.CommonConstant;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * 微信小程序用户接口
 *
 */
@RestController
@RequestMapping("/bytedance/user/{appid}")
@Api(tags = "字节跳动 - 登录接口")
public class BdMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BdMaProperties properties;

    @Autowired
    StaffService staffService;

    @Autowired
    MemVerificationCache cache;

    @Autowired
    BDRemoteCallService remoteCallService;

    @GetMapping("/login")
    public StatusResponse login(@RequestHeader(name = "clientSystem",required = false) String clientSystem,
                                @RequestHeader(name = "clientVersion",required = false) String clientVersion,
                                @RequestHeader(name = "ipAddress",required = false) String ipAddress,
                                @PathVariable String appid,
                                String code) {

        if (StringUtils.isBlank(code)) {
            return StatusResponse.error(ErrorCode.UNDEFINED,"empty jscode");
        }

        BdMaProperties.Config config = null;

        for (BdMaProperties.Config c : properties.getConfigs()){
            if (c.getAppid().equals(appid)){
                config = c;
                break;
            }
        }

        if (config == null){
            throw new BusinessException(ErrorCode.UNDEFINED, "不支持的appid");
        }

        BDCode2SessionRequest request = new BDCode2SessionRequest();
        request.setAppid(config.getAppid());
        request.setSecret(config.getSecret());
        request.setCode(code);

        BDCode2SessionResponseData session = remoteCallService.requestSession2Code(request);
        if (session == null){
            throw new BusinessException(ErrorCode.VERSION_ERROR, "请求字节跳动服务器响应错误");
        }

        this.logger.info(session.getSession_key());
        this.logger.info(session.getOpenid());
        this.logger.info(session.getUnionid());

        ///
        Staff user = null;
        if( StringUtils.isNotEmpty(session.getUnionid())){
            user = staffService.getUnionID(session.getUnionid(), appid);
        }
        if(user == null){  // unionid找不到，就用openid 找
            user = staffService.getOpenIDMA(session.getOpenid(), appid);
            if (user != null && user.getTemporally()){  //取消临时账号
                user.setTemporally(false);
            }
        }
        if (Objects.isNull(user)) {
            //String realName, String mobile, Integer gender, String areaName, String address, String areaId
            user = staffService.add(session.getOpenid(), null, session.getUnionid(), session.getSession_key(), appid,
                    CommonConstant.Platform.WXMA);
        }else{
            user = staffService.updateSessionKey(user, session.getUnionid(), session.getSession_key());
        }

        Map<String, Object> result = Maps.newHashMap();
        result.put("user", StaffVO.of(user, staffService.staffOrgnization(user)));

        String ticket = cache.produceTicket(user.getId(), CommonConstant.Platform.WXMA.codeOf());
        result.put("ticket", ticket);

        result.put("session", session);

        ///
        return StatusResponse.success(result);

    }

}
